﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;

using RexToy.Xml;

namespace RexToy.UI.WinForm.Pmlx
{
    class Style
    {
        public static readonly Style None = new Style();

        private XAccessor _x;
        private bool _empty;
        internal Style(XAccessor x)
        {
            _x = x;
        }

        internal Style()
        {
            _empty = true;
        }

        public void ApplyToControl(Control c, ControlMetaData meta)
        {
            if (_empty)
                return;
            else
            {
                IReflector r = Reflector.Bind(c);
                foreach (var attr in _x.Attributes)
                {
                    if (!string.IsNullOrEmpty(_x.Prefix))
                        ExceptionHelper.ThrowAttributeHavePrefix(_x.Prefix, _x.LocalName);

                    if (attr.LocalName == ControlSizeHelper.HEIGHT || attr.LocalName == ControlSizeHelper.WIDTH)
                    {
                        ControlSizeHelper.SetSize(c, attr.LocalName, attr.GetStringValue(), meta);
                        continue;
                    }

                    attr.ApplyValue(r);
                }
            }
        }

        public void ApplyToInstance(object instance)
        {
            if (_empty)
                return;
            else
            {
                IReflector r = Reflector.Bind(instance);
                foreach (var attr in _x.Attributes)
                {
                    if (!string.IsNullOrEmpty(_x.Prefix))
                        ExceptionHelper.ThrowAttributeHavePrefix(_x.Prefix, _x.LocalName);

                    attr.ApplyValue(r);
                }
            }
        }
    }
}
